<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i>后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>新增SPU</el-breadcrumb-item>
      <el-breadcrumb-item>{{$router.currentRoute.name}}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
      <el-form-item label="相册" prop="albumId">
        <el-select v-model="ruleForm.albumId" placeholder="请选择相册" style="width: 300px;" @change="loadPictureList">
          <el-option
              v-for="item in albumListOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="ruleForm.albumId">
        <div v-if="pictureList.length>0">
          <el-image class="picture-item"
                    v-for="picture in pictureList"
                    :key="picture.id"
                    :src="picture.url"
                    fit="cover"></el-image>
        </div>
        <div v-else>
          <div class="text-warning">注意：此相册中无图片，请选择其它相册，或前往 <a href="/sys-admin/product/album">相册管理</a> 以添加图片。</div>
          <div class="text-info">提示：您的前序操作已经被保存在本地。</div>
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="warning" @click="backToPreStep()">上一步</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">下一步</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  data() {
    return {
      albumListOptions: [],
      pictureList: [],
      ruleForm: {},
      //表单规则
      rules: {
        albumId: [
          {type: 'number', required: true, message: '请选择相册', trigger: 'blur'},
        ]
      }
    }
  },
  methods: {
    //加载相册列表
    loadAlbumList() {
      let url = "http://localhost:9180/albums?queryType=all";

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.albumListOptions = jsonResult.data.list;
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    //加载相册列表
    loadPictureList(albumId) {
      if (albumId) {
        let url = "http://localhost:9180/pictures/list-by-album?queryType=all&albumId=" + albumId;

        let localJwt = localStorage.getItem('localJwt');
        this.axios.create({'headers': {'Authorization': localJwt}})
            .get(url).then((response) => {
          let jsonResult = response.data;
          if(jsonResult.state == 20000){
            this.pictureList = jsonResult.data.list;
          }else{
            this.$alert(jsonResult.message, '错误', {
              confirmButtonText: '确定',
              callback: action => {
                this.$router.push('/sys-admin/product/album');
              }
            });
          }
        });
      }
    },
    // 加载本地存储的表单数据
    loadLocalRuleForm() {
      let localRuleFormString = localStorage.getItem('localRuleForm');
      let localRuleForm = JSON.parse(localRuleFormString);
      //第一步数据不存在
      if(!localRuleForm || !localRuleForm.categoryId){
        this.$router.push("add-new-1");
        return;
      }
      //第二步数据不存在
      if(!localRuleForm.brandId){
        this.$router.push("add-new-2");
        return;
      }

      this.ruleForm = localRuleForm;
      this.loadPictureList(this.ruleForm.albumId);
    },
    submitForm(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let pictureListJsonString = JSON.stringify(this.pictureList);
          if (pictureListJsonString.length > 1000) {
            let message = '您选择的相册中图片数量超出了限制，请更换或调整相册！';
            this.$alert(message, '警告', {
              confirmButtonText: '确定',
              callback: action => {
              }
            });
            return;
          }

          let url = "http://localhost:9180/albums/" + this.ruleForm.albumId;
          console.log('url = ' + url);

          let localJwt = localStorage.getItem('localJwt');
          this.axios.create({'headers': {'Authorization': localJwt}})
              .get(url).then((response) => {
            let jsonResult = response.data;
            if(jsonResult.state == 20000){
              let album = jsonResult.data;
              this.ruleForm.albumName = album.name;
              this.ruleForm.pictures = pictureListJsonString;
              let ruleForm = JSON.stringify(this.ruleForm);
              localStorage.setItem("localRuleForm", ruleForm);
              this.$router.push('add-new-4');
            }else if(jsonResult.state == 40400){
              this.$alert(jsonResult.message, '错误', {
                confirmButtonText: '确定',
                callback: action => {
                  this.loadAlbumList();
                }
              });
            }else{
              this.$alert(jsonResult.message, '错误', {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //返回上一步
    backToPreStep(){
      this.$router.push("add-new-2");
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  mounted() {
    this.loadLocalRuleForm();
    this.loadAlbumList();
  }
}
</script>

<style>
.picture-item {
  width: 180px;
  height: 180px;
  margin-right: 20px;
  margin-bottom: 20px;
  border-radius: 6px;
  float: left;
}

.text-warning {
  color: #F56C6C;
}

.text-warning a {
  color: #409EFF;
}

.text-info {
  color: #409EFF;
}
</style>